package com.sccl.autojob.util.convert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 常用的转化类
 * @Auther Huang Yongxiang
 * @Date 2021/12/01 10:39
 */
public class ConvertUtil {
    private static final Logger logger = LoggerFactory.getLogger(ConvertUtil.class);
    //日期型正则
    private static final Pattern date1 = Pattern.compile("^\\d{4}/\\d{1,2}/\\d{1,2}");
    private static final Pattern date2 = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2}");
    private static final Pattern date3 = Pattern.compile("^\\d{4}.\\d{1,2}.\\d{1,2}");

    //数字正则表达
    private static final Pattern data = Pattern.compile("^(\\-|\\+)?\\d+(\\.\\d+)?$");
    //小数正则式表达
    private static final Pattern decimal = Pattern.compile("^-?(\\d+)(\\.\\d+)$");

    /**
     * @param dateStr 日期字符串，目前支持yyyy/MM/dd、yyyy-MM-dd、yyyy.MM.dd
     * @param addnum  增加的天数，为负表示减少天数
     * @param format  返回的格式化日期字符串
     * @return java.lang.String
     * @description 对日期字符串加减addnum天
     * @author Huang Yongxiang
     * @date 2021/8/5 14:56
     */
    public static String addDate(String dateStr, int addnum, String format) {
        if (StringUtils.isEmpty(dateStr)) {
            return "";
        }
        Matcher matcher1 = date1.matcher(dateStr);
        Matcher matcher2 = date2.matcher(dateStr);
        Matcher matcher3 = date3.matcher(dateStr);
        String match1 = "yyyy/MM/dd";
        String match2 = "yyyy-MM-dd";
        String match3 = "yyyy.MM.dd";
        if (!matcher1.matches() && !matcher2.matches() && !matcher3.matches()) {
            System.out.println("日期:" + dateStr + "不合法，转换失败！");
            return "";
        }

        Date date = null;
        SimpleDateFormat simpleDateFormat = null;
        if (matcher1.matches()) {
            simpleDateFormat = new SimpleDateFormat(match1);
            try {
                date = simpleDateFormat.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (matcher2.matches()) {
            simpleDateFormat = new SimpleDateFormat(match2);
            try {
                date = simpleDateFormat.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (matcher3.matches()) {
            simpleDateFormat = new SimpleDateFormat(match3);
            try {
                date = simpleDateFormat.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        SimpleDateFormat fm = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, addnum);
        return fm.format(calendar.getTime());
    }

    /**
     * 在给定日期字符串的上月份加1返回
     *
     * @param dateStr   日期字符串
     * @param inFormat  输入的日期格式
     * @param addMonth  要增加的月份数
     * @param outFormat 输出的日期格式
     * @return java.lang.String
     * @author Huang Yongxiang
     * @date 2021/12/1 13:54
     */
    public static String addMonth(String dateStr, String inFormat, int addMonth, String outFormat) {
        if (StringUtils.isEmpty(dateStr) || StringUtils.isEmpty(inFormat) || StringUtils.isEmpty(outFormat)) {
            logger.error("参数错误！");
            return null;
        }
        String resultStr = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat(inFormat);
            Date date = format.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, addMonth);
            SimpleDateFormat out = new SimpleDateFormat(outFormat);
            resultStr = out.format(calendar.getTime());

        } catch (ParseException e) {
            logger.error("日期转换错误，请检查inFormat参数是否符合格式");
            e.printStackTrace();
        }
        return resultStr;
    }

    public static String addTime(String dateStr, String inFormat, long addTime, String outFormat) {
        if (StringUtils.isEmpty(dateStr) || StringUtils.isEmpty(inFormat) || StringUtils.isEmpty(outFormat)) {
            logger.error("参数错误！");
            return null;
        }
        String resultStr = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat(inFormat);
            Date date = format.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int add = 0;
            if (addTime > Integer.MAX_VALUE) {
                add = (int) (addTime % 2 == 0 ? addTime / 2 : (addTime - 1) / 2);
            }
            if (add == 0) {
                calendar.add(Calendar.MILLISECOND, (int) addTime);
            } else {
                calendar.add(Calendar.MILLISECOND, add);
                calendar.add(Calendar.MILLISECOND, add);

            }
            SimpleDateFormat out = new SimpleDateFormat(outFormat);
            resultStr = out.format(calendar.getTime());

        } catch (ParseException e) {
            logger.error("日期转换错误，请检查inFormat参数是否符合格式");
            e.printStackTrace();
        }
        return resultStr;
    }

    public static void main(String[] args) {
        String res = addTime("2021-12-11 14:00:00", "yyyy-MM-dd HH:mm:ss", 1000 * 60, "yyyy-MM-dd HH:mm:ss");
        System.out.println(res);
    }

    /**
     * 将时间字符串转换为时间戳
     *
     * @param dateStr yyyy-mm-dd格式
     */
    public static Long convertDateToInt(String dateStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return -1L;
        }
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date != null) return date.getTime();
        else return null;
    }

    public static long convertDateToLong(String dateStr, String format) {
        if (StringUtils.isEmpty(dateStr)) {
            return -1L;
        }
        Date date = null;
        if (!StringUtils.isEmpty(format)) {
            try {
                date = new SimpleDateFormat(format).parse(dateStr);
                if (date == null) {
                    date = convertDate(dateStr);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (date != null) {
            return date.getTime();
        }
        return -1;
    }

    /**
     * 尝试对日期字符串进行转化，可指定尝试的转化格式
     *
     * @param dateString 日期字符串
     * @param formats    日期字符串可能的格式，不指定时会使用常用的格式对其进行尝试转化
     * @return java.util.Date
     * @author Huang Yongxiang
     * @date 2022/1/12 9:54
     */
    public static Date convertDate(String dateString, String... formats) {
        if (StringUtils.isEmpty(dateString)) {
            logger.error("日期字符串为null，转换失败");
            return null;
        }
        if (formats == null || formats.length == 0) {
            logger.warn("日期格式指定为空，将尝试使用常见日期格式对其转化");
            formats = new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss", "yyyy.MM.dd HH:mm:ss", "yyyy/MM/dd", "yyyy-MM-dd", "yyyy.MM.dd", "yyyyMMdd",};
        }
        Date parse = null;
        for (String format : formats) {
            try {
                if ("yyyyMMdd".equals(format) && !RegexUtil.isMatch(dateString, "^\\d{8}$")) {
                    continue;
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
                parse = simpleDateFormat.parse(dateString);
                if (parse != null) {
                    logger.info("使用{}格式对日期字符串：{}转化成功", format, dateString);
                    break;
                }
            } catch (ParseException e) {
                logger.debug("尝试使用{}格式对日期字符串：{}进行转化失败，将使用下一个格式尝试转化", format, dateString);
            }
        }
        if (parse == null) {
            logger.error("日期字符串：{}尝试转化失败", dateString);
            return null;
        }
        return parse;
    }

    /**
     * 把long型转为日期型
     *
     * @param date   毫秒数
     * @param format 要转为的日期字符串的类型
     * @return
     */
    public static String convertIntToDate(long date, String format) {
        if (StringUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date d = new Date(date);
        return simpleDateFormat.format(d);
    }

    public static Class<?> classNameToClass(String className) {
        if (StringUtils.isEmpty(className)) {
            return null;
        }
        Class<?> clazz = null;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            logger.error("没有找到指定类{}", className);
            e.printStackTrace();
        }
        return clazz;
    }


}
